import { floorNumber, numberFormat } from '@/utils/index.js'

// 绘制圆角矩形
export const drawRoundRect = (ctx, x, y, width, height, radius, color) => {
	ctx.save()
	ctx.beginPath()
	ctx.setFillStyle(color) 
	// ctx.setStrokeStyle(color)
	ctx.setStrokeStyle('transparent')
	ctx.setLineJoin('round')  //交点设置成圆角
	ctx.setLineWidth(radius)
	ctx.strokeRect(x + radius/2, y + radius/2, width - radius , height - radius )
	ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2)
	// ctx.stroke()
	ctx.closePath()
	ctx.restore()
}

// 绘制带圆角图片
export const drawRoundImg = (ctx, img, x, y, width, height, radius) => {
	ctx.beginPath()
	ctx.save()
	// 左上角
	ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
	// 右上角
	ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
	// 右下角
	ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
	// 左下角
	ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
	// ctx.stroke()
	ctx.clip()
	ctx.drawImage(img, x, y, width, height)
	ctx.restore()
	ctx.closePath()
}

// 绘制带圆角图片
export const drawRoundImgfit = (ctx, img, imgWidth, imgHeight, x, y, width, height, radius) => {
	ctx.beginPath()
	ctx.save()
	// 左上角
	ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
	// 右上角
	ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
	// 右下角
	ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
	// 左下角
	ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
	// ctx.stroke()
	ctx.clip()
	
	const scaleX = imgWidth / width
	const scaleY = imgHeight / height
	const minScale = numberFormat(Math.min(scaleX, scaleY))
	console.log('缩放比例', scaleX, scaleY, minScale, imgWidth, imgHeight, width, height)
	let imgX = 0
	let imgY = 0
	// console.log('图片宽高：', imgWidth, imgHeight)
	// console.log('画布宽高', width, height)
	const imgCx = imgWidth / 2
	const imgCy = imgHeight / 2
	imgX = Math.floor(imgCx - (width * minScale) / 2)
	imgY = Math.floor(imgCy - (height * minScale) / 2)
	// console.log('图片开始点', imgX, imgY)
	if (imgX < 0) {
		imgY += Math.floor(Math.abs(imgX) * height / width)
		imgX = 0
	}
	if (imgY < 0) {
		imgX += Math.floor(Math.abs(imgY) * width / height)
		imgY = 0
	}
	imgX = Math.floor(imgX)
	imgY = Math.floor(imgY)
	// console.log('修改后的图片开始点', imgX, imgY)
	
	ctx.drawImage(img, imgX, imgY, Math.floor(width * minScale), Math.floor(height * minScale), x, y, width, height)
	ctx.restore()
	ctx.closePath()
}

/**
 * text	要绘制的文本内容
 */
export const textPrewrap = (ctx, text, x, y, lineHeight, lineMaxWidth, lineNum) => {
	let drawTxt = '' // 当前绘制的内容
	let drawLine = 1 // 第几行开始绘制
	let drawIndex = 0 // 当前绘制内容的索引
	// 判断内容是否可以一行绘制完毕
	// console.log('是否一行', ctx.measureText(text).width, lineMaxWidth)
	if (ctx.measureText(`${text}`).width <= lineMaxWidth) {
		ctx.fillText(text, x, y)
	} else {
		for (let i = 0; i < text.length; i++) {
			// console.log(i, drawIndex, drawTxt, ctx.measureText(drawTxt).width, drawLine)
			if (ctx.measureText(drawTxt + text[i]).width > lineMaxWidth) {
				if (drawLine === lineNum) {
					// 最后一行添加省略号
					ctx.fillText(text.substring(drawIndex, i - 1) + '...', x, y)
					break
				} else {
					ctx.fillText(text.substring(drawIndex, i), x, y)
					drawIndex = i // 记录当前行最后一个字符串的下一个index, 用于绘制下行第一个字
					drawLine += 1 // 行数+1
					y += lineHeight // 绘制内容的y坐标对应增加行高
					drawTxt = '' // 重置绘制的内容
				}
				i-- // 宽度超出，回退一个字符
			} else {
				drawTxt += text[i]
				if (drawLine === lineNum && i === text.length - 1) {
					// 最后一行没有超出
					ctx.fillText(drawTxt, x, y)
				}
			}
		}
	}
	return drawLine
}

// 将Base64写入本地文件
export const base64WriteFile = (filePath, data) => {
	const fs = uni.getFileSystemManager()
	return new Promise((resolve, reject) => {
		fs.writeFile({
			filePath,
			data,
			encoding: 'base64',
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err)
			},
		})
	})
}

// 加载图片地址，生成base64并写入临时路径中
export const getImgBase64 = async (params) => {
	const { src, canvasWidth, filePath } = params
	try{
		const fs = uni.getFileSystemManager()
		const imgInfo = await uni.getImageInfo({
			src,
		})
		const imageWidth = canvasWidth * 0.8 // 随意定，多少px都行
		// 根据比例计算图片在画布中的高度
		const scaleFactor = Number((imageWidth / imgInfo.width).toFixed(2))
		// 根据比例计算图片高度
		const imageHeight = imgInfo.height * scaleFactor
		const base64 = fs.readFileSync(imgInfo.path, 'base64')
		await base64WriteFile(filePath, base64)
		const currentImgInfo = await uni.getImageInfo({
			src: filePath,
		})
		return {
			imageWidth,
			imageHeight,
			imgUrl: currentImgInfo.path
		}
	}catch(e) {
		console.log('err', e)
	}
}

// 绘制自定义圆角矩形
export const drawRoundedRect = (ctx, x, y, w, h, params) => {
	const {
		leftTop = false,
		leftBottom = false,
		rightTop = false,
		rightBottom = false,
		fillColor = 'transparent',
		r = 0,
	} = params || {}
	ctx.save() // 保存当前绘图状态 防止虚线影响其他图形
	ctx.beginPath()
	ctx.setFillStyle(fillColor)
	ctx.setStrokeStyle('transparent')
	ctx.moveTo(x + r, y)
	// 绘制上边线和左上角圆弧
	if (leftTop) {
		ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
		ctx.lineTo(x, y)
	} else {
		ctx.moveTo(x, y + r)
		ctx.lineTo(x, y)
		ctx.lineTo(x + r, y)
	}
	ctx.lineTo(x + w - r, y)
	// 绘制上边线和右上角圆弧
	if (rightTop) {
		ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
	} else {
		ctx.lineTo(x + w - r, y)
		ctx.lineTo(x + w, y)
		ctx.lineTo(x + w, y + r)
	}
	ctx.lineTo(x + w, y + h - r)
	// 绘制下边线和右下角圆弧
	if (rightBottom) {
		ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
	} else {
		ctx.lineTo(x + w, y + h - r)
		ctx.lineTo(x + w, y + h)
		ctx.lineTo(x + w - r, y + h)
	}
	ctx.lineTo(x + r, y + h)
	// 绘制下边线和左下角圆弧
	if (leftBottom) {
		ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
	} else {
		ctx.lineTo(x + r, y + h)
		ctx.lineTo(x, y + h)
		ctx.lineTo(x, y + h - r)
	}
	ctx.lineTo(x, y + r)
	// 绘制左边线和左上角圆弧
	if(leftTop) {
		ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
		ctx.moveTo(x + r, y)
	} else {
		ctx.moveTo(x, y + r)
		ctx.lineTo(x, y)
		ctx.lineTo(x + r, y)
	}
	ctx.fill()
	ctx.closePath()
	ctx.stroke()
	ctx.restore() // 恢复之前的绘图状态
}

// 绘制文本
export const drawText = (ctx, text, config) => {
	const { fillStyle, fontSize, x, y, center = false } = config
	ctx.setFillStyle(fillStyle)
	ctx.setFontSize(fontSize)
	if (center) {
		ctx.textAlign = 'center'
	}
	ctx.fillText(text, x, y)
}

// 文本自动换行
export const drawText2 = (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) => {
	let lineWidth = 0
	let lastSubStrIndex = 0
	for (let i = 0; i < str.length; i++) {
		lineWidth += ctx.measureText(str[i]+' ').width
		if (lineWidth > canvasWidth) {
			ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight)
			initHeight += 16 // 16为字体的高度
			lastSubStrIndex = i
			titleHeight += 30
		}
		if (i == str.length - 1) {
			ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight)
		}
	}
	titleHeight = titleHeight + 10
	return titleHeight
}

// rpx转px
export const rpxToPx = (rpx) => {
	const screenWidth = uni.getSystemInfoSync().screenWidth
	console.log('screen', screenWidth, (screenWidth * Number.parseInt(rpx)) / 750)
	return (screenWidth * Number.parseInt(rpx)) / 750
}

/**
 * @description: 获取设备信息
 * @param {type}
 * @return {type}
 * @author: hch
 */
export function getSystem() {
  let system = wx.getSystemInfoSync()
  let scale = system.windowWidth / 375 //按照苹果留 375*667比例 其他型号手机等比例缩放 显示
  return { w: system.windowWidth, h: system.windowHeight, scale: scale }
}